package com.LiL.Wayne.Activity.fragment;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.LiL.Wayne.Activity.R;
import com.LiL.Wayne.Activity.R.anim;
import com.LiL.Wayne.Activity.R.id;
import com.LiL.Wayne.Activity.R.layout;
import com.LiL.Wayne.Activity.activity.PlayList_Interface;
import com.LiL.Wayne.Activity.activity.SelectPlaylist;
import com.audamob.audasingers.model.PlayList;

public class SwipeyTabFragmentMusicPlayList extends Fragment {
	private SimpleDateFormat FormatterDuration = new SimpleDateFormat("mm:ss");
	public static SwipeyTabFragmentMusicPlayList f;

	public static Fragment newInstance(String title) {
		f = new SwipeyTabFragmentMusicPlayList();
		Bundle args = new Bundle();
		args.putString("title", title);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
	}

	public static ListView ListVideo;
	static EditText SearchEdit;
	static ArrayList<PlayList> PlaylistMusicList;
	ArrayList<PlayList> AllLyricList;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		ViewGroup root = (ViewGroup) inflater.inflate(
				R.layout.layout_activity_playlist, null);
		final String title = getArguments().getString("title");
		PlaylistMusicList = new ArrayList<PlayList>();
		try {
			PlaylistMusicList = restorePlayListList_main();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d("Playlist",
				" bdina taille il playlist= " + PlaylistMusicList.size());
		AllLyricList = new ArrayList<PlayList>();
		AllLyricList.addAll(PlaylistMusicList);
		Log.d("Playlist", " marra okhra taille il playlist= "
				+ PlaylistMusicList.size());
		ListVideo = (ListView) root.findViewById(R.id.ListAppPLL);
		ListVideo.setAdapter(new AppAdapter());
		SearchEdit = (EditText) root.findViewById(R.id.searcheditplaylist);
		ThreadUpdateList th = new ThreadUpdateList(handlerLoad);
		th.start();

		ImageView iv = (ImageView) root.findViewById(R.id.icon_add_video);
		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getActivity().getBaseContext(),
						SelectPlaylist.class);

				getActivity().startActivityForResult(i, 3);
			}
		});
		return root;

	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}

	final Handler handlerLoad = new Handler() {

		public void handleMessage(Message msg) {

			try {
				PlaylistMusicList.clear();
				Log.e("Songs", "AllLyric size " + AllLyricList.size());
				for (int i = 0; i < AllLyricList.size(); i++) {

					if (AllLyricList
							.get(i)
							.getName()
							.toLowerCase()
							.contains(
									("" + SearchEdit.getText().toString())
											.toLowerCase())) {

						PlaylistMusicList.add(AllLyricList.get(i));

					}
				}
				Log.e("Songs", "change :: " + PlaylistMusicList.size());
				ListVideo = (ListView) getActivity().findViewById(
						R.id.ListAppPLL);
				ListVideo.setAdapter(new AppAdapter());
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	};

	int EditSongNameTextlength = 0;
	int EditAlbumNameTextlength = 0;

	private class ThreadUpdateList extends Thread {
		Handler mHandler;
		boolean Done = false;

		ThreadUpdateList(Handler h) {
			mHandler = h;
		}

		public void run() {
			while (!Done) {
				try {
					currentThread().sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// Log.e("Songs","change : "+SearchEdit.getText().length());
				if (SearchEdit.getText().length() == EditSongNameTextlength) {
				} else {
					Log.e("Songs", "change");
					EditSongNameTextlength = SearchEdit.getText().length();

					Message msg = mHandler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("url", "");
					msg.setData(b);
					mHandler.sendMessage(msg);
				}
			}
		}
	}

	public class AppAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public AppAdapter() {
			mInflater = (LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return PlaylistMusicList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			final ViewHolderImage holder;
			if (convertView == null) {
				holder = new ViewHolderImage();

				convertView = mInflater.inflate(R.layout.auda_item_playlist, null);

				holder.Name = (TextView) convertView.findViewById(R.id.nam);
				holder.size = (TextView) convertView.findViewById(R.id.Number);
				holder.ItemSong = (RelativeLayout) convertView
						.findViewById(R.id.ItemSong);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolderImage) convertView.getTag();
			}

			holder.Name.setId(position);
			holder.size.setId(position);
			holder.ItemSong.setId(position);

			holder.ItemSong.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(getActivity().getBaseContext(),
							PlayList_Interface.class);
					i.putExtra("position", position);
					getActivity().startActivity(i);
					getActivity().overridePendingTransition(
							R.anim.push_down_in, R.anim.push_down_out);
				}
			});
			/*
			 * holder.play.setOnClickListener(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { // TODO Auto-generated
			 * method stub Intent i=new
			 * Intent(getActivity().getBaseContext(),MusicPlayer.class);
			 * i.putExtra("name",""); i.putExtra("album",""); i.putExtra("mode",
			 * 2); i.putExtra("ID", position); getActivity().startActivity(i); }
			 * });
			 */

			holder.Name.setText(PlaylistMusicList.get(position).getName());
			holder.size.setText(PlaylistMusicList.get(position).getListMusic()
					.size()
					+ " songs");
			holder.id = position;

			return convertView;
		}
	}

	class ViewHolderImage {

		TextView Name;
		TextView size;
		RelativeLayout ItemSong;
		int id;
	}

	public ArrayList<PlayList> restorePlayListList() throws IOException,
			ClassNotFoundException {
		FileInputStream fin = new FileInputStream(getActivity().getCacheDir()
				.getAbsolutePath() + "/playlistlist");
		ObjectInputStream in = new ObjectInputStream(fin);
		ArrayList<PlayList> object = (ArrayList<PlayList>) in.readObject();
		in.close();
		return object;
	}

	public static ArrayList<PlayList> restorePlayListList_Global()
			throws IOException, ClassNotFoundException {
		FileInputStream fin = new FileInputStream(f.getActivity().getCacheDir()
				.getAbsolutePath()
				+ "/playlistlist");
		ObjectInputStream in = new ObjectInputStream(fin);
		ArrayList<PlayList> object = (ArrayList<PlayList>) in.readObject();
		in.close();
		return object;
	}

	public ArrayList<PlayList> restorePlayListList_main() throws IOException,
			ClassNotFoundException {
		FileInputStream fin = new FileInputStream(getActivity().getCacheDir()
				.getAbsolutePath() + "/playlistlist");
		ObjectInputStream in = new ObjectInputStream(fin);
		ArrayList<PlayList> object = (ArrayList<PlayList>) in.readObject();
		in.close();
		return object;
	}

	public static void sauvegardPlayListList(ArrayList<PlayList> s)
			throws IOException {
		FileOutputStream fout = new FileOutputStream(f.getActivity()
				.getCacheDir().getAbsolutePath()
				+ "/playlistlist");
		ObjectOutputStream out = new ObjectOutputStream(fout);

		out.writeObject(s);
		out.close();
	}

	@Override
	public void onResume() {
		super.onResume();
		// TODO Auto-generated method stub
		update_your_sel2();
	}

	public static void update_your_sel() {
		// TODO Auto-generated method stub
		PlaylistMusicList = new ArrayList<PlayList>();
		try {
			PlaylistMusicList = restorePlayListList_Global();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ListVideo = (ListView) f.getActivity().findViewById(R.id.ListAppPLL);
		ListVideo.setAdapter(f.new AppAdapter());
	}

	public void update_your_sel2() {
		// TODO Auto-generated method stub
		PlaylistMusicList = new ArrayList<PlayList>();
		try {
			PlaylistMusicList = restorePlayListList();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ListVideo = (ListView) getActivity().findViewById(R.id.ListAppPLL);
		ListVideo.setAdapter(new AppAdapter());
	}

	// ****************************************
	// EDIT MODE
	// ****************************************

	public static void Mode_Edit() {
		SearchEdit.setEnabled(false);
		HideImageImageselection = new boolean[PlaylistMusicList.size()];

		AppAdapterEdit ad = f.new AppAdapterEdit();

		ListVideo.setAdapter(ad);

	}

	private static boolean[] HideImageImageselection;

	public class AppAdapterEdit extends BaseAdapter {
		private LayoutInflater mInflater;

		public AppAdapterEdit() {
			mInflater = (LayoutInflater) getActivity().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return PlaylistMusicList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolderImage_edit holder;
			if (convertView == null) {
				holder = new ViewHolderImage_edit();

				convertView = mInflater.inflate(R.layout.item_custom_edit_p,
						null);
				holder.checkbox = (CheckBox) convertView
						.findViewById(R.id.checkbox);

				holder.Name = (TextView) convertView.findViewById(R.id.nam);
				holder.Number = (TextView) convertView
						.findViewById(R.id.Number);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolderImage_edit) convertView.getTag();
			}
			holder.checkbox.setId(position);

			holder.Name.setId(position);
			holder.Number.setId(position);
			holder.checkbox.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					CheckBox cb = (CheckBox) v;
					int id = cb.getId();
					if (HideImageImageselection[id]) {
						cb.setChecked(false);
						HideImageImageselection[id] = false;
					} else {
						cb.setChecked(true);
						HideImageImageselection[id] = true;
					}
				}
			});

			holder.checkbox.setChecked(HideImageImageselection[position]);
			holder.Name.setText(PlaylistMusicList.get(position).getName());
			holder.Number.setText(PlaylistMusicList.get(position)
					.getListMusic().size()
					+ " songs");
			holder.id = position;

			return convertView;
		}
	}

	class ViewHolderImage_edit {
		CheckBox checkbox;

		TextView Name;
		TextView Number;
		int id;
	}

	public static void Mode_Edit_of() {
		SearchEdit.setEnabled(true);
		ArrayList<PlayList> list = new ArrayList<PlayList>();

		for (int j = 0; j < PlaylistMusicList.size(); j++) {

			if (HideImageImageselection[j]) {

			} else {
				list.add(PlaylistMusicList.get(j));
			}

		}
		try {
			sauvegardPlayListList(list);

		} catch (Exception e) {
			// TODO: handle exception
		}

		update_your_sel();

	}
}